﻿using System;
using System.Web.Mvc;
using System.Web.Security;
using log4net;
using TheBullysStore.Models.ModuloAdministracion.Login;

namespace TheBullysStore.Controllers.ModuloAdministracion
{
    public class LoginController : Controller
    {
        //
        // GET: /Login/
        private static ILog log = LogManager.GetLogger(typeof(LoginController));
        LoginModelDAO loginDAO = new LoginModelDAO();

        public ActionResult Index()
        {
            return View();
        }

        public ActionResult Login() {
            return View();
        }

        public ActionResult HomeIntranet() {
            ViewBag.Message = "Bienvenidos a SoftBully";
            return View();
        
        }

        [HttpPost]
        public ActionResult Login(LoginModel login) {
            FormsAuthentication.SignOut(); 
            if (ModelState.IsValid) {
                if (LoginModelDAO.comprobarLogin(login))
                {
                    FormsAuthentication.SetAuthCookie(login.usuario, false);

                    return RedirectToAction("HomeIntranet", "Home");
                    
                }
                else {
                    ModelState.AddModelError("", "Usuario y/o Constrasenia incorrectos");
                }
            }
                
            return View();
        }

        [HttpPost]
        public JsonResult LoginResult(LoginModel login)
        {
            try
            {
                var usuario = loginDAO.getLogin(login);
                if (usuario != null)
                {
                    FormsAuthentication.SetAuthCookie(login.usuario, false);
                }
                return new JsonResult() { Data = usuario };
            }
            catch (Exception ex)
            {
                log.Error("Login - GET(EXCEPTION):", ex);
                return Json(new { Data = "Ocurrió un error en el Login" });
            }
        }
    }
}
